import type { BaseResponse } from '../models/up_response.ts';
import type {
  EEPromParamWriteRequest,
  EEPromParamWrite,
} from '../models/up_request.ts';
import { SerialPortFactory } from '../models/factories/SerialPortFactory';
import apiClient from '../utils/axiosInterceptors';

export class WriteService {
  /** 通用 POST 并校验 status */
  private static async postStatus(url: string, data: any): Promise<boolean> {
    const response = await apiClient.post<BaseResponse<unknown>>(url, data);
    if (response.data.status) {
      return true;
    }
    throw SerialPortFactory.createSerialError(
      response.data.message || 'Unknown error'
    );
  }

  static writeEEProm(
    serial_id: string,
    protocol_id: number,
    param: EEPromParamWrite,
    value: number
  ): Promise<boolean> {
    const request: EEPromParamWriteRequest = {
      serial_id,
      protocol_id,
      param,
      value,
    };
    return this.postStatus('/write/eeprom_param', request);
  }

  static sendAccelerationDeceleration(
    serial_id: string,
    protocol_id: number,
    acceleration: number,
    deceleration: number
  ): Promise<boolean> {
    return this.postStatus(
      '/write/acceleration_deceleration',
      SerialPortFactory.createAccelerationDecelerationRequest(
        serial_id,
        protocol_id,
        acceleration,
        deceleration
      )
    );
  }
}
